package cn.com.shuyangyang.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.com.shuyangyang.common.Context;
import cn.com.shuyangyang.common.RequestContext;
import cn.com.shuyangyang.controller.response.ApplicationErrorResponse;
import cn.com.shuyangyang.controller.response.EmptyResponse;
import cn.com.shuyangyang.controller.response.ExceptionResponse;
import cn.com.shuyangyang.controller.response.NormalResponse;
import cn.com.shuyangyang.controller.response.Response;
import cn.com.shuyangyang.domain.EnumStatus;
import cn.com.shuyangyang.domain.LoginLog;
import cn.com.shuyangyang.domain.MessAge;
import cn.com.shuyangyang.domain.MessageVo;
import cn.com.shuyangyang.domain.UserMessage;
import cn.com.shuyangyang.service.MessageService;
import cn.com.shuyangyang.service.UserMessageService;
import cn.com.shuyangyang.util.BaseUtil;

/**消息管理控制
 * @author shuyangyang
 * @E-Mail:shuyangyang@aliyun.com
 * @Bolg:http://www.shuyangyang.com.cn
 * @date 2016年9月14日 上午9:33:02
 */
@Controller
@RequestMapping("/message/")
public class MessageController {
	
	Logger	logger	= LoggerFactory.getLogger(MessageController.class);
	
	@Autowired
	private UserMessageService userMessageService;
	
	@Autowired
	private MessageService messageService;

	/**
	 * 显示所有收件箱消息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("allMessage")
	@ResponseBody
	public Response loadAllMessage(HttpServletRequest request,HttpServletResponse response) {
		String start = request.getParameter("start");//起始页
        String limit = request.getParameter("limit");//每页数量
        String dirtype = request.getParameter("dirtype");
        int index = Integer.parseInt(start);  
        int pageSize = Integer.parseInt(limit);
		try {
			LoginLog loginLogInfo = (LoginLog) request.getSession().getAttribute("loginLogInfo");
			String receverid = loginLogInfo.getLoginName();
			List<UserMessage> messages = null;
			//收件箱
			if(dirtype.equals("inBox")){
				messages = userMessageService.getAllUncollectedMail(receverid,index,pageSize);
			}else if(dirtype.equals("draFts")){
				//草稿箱
				messages = userMessageService.getDraFtsMail(receverid,index,pageSize);
			}else if(dirtype.equals("sentMessage")){
				//已发送消息
				messages = userMessageService.getSentMessageMail(receverid,index,pageSize);
			}else if(dirtype.equals("deletedMessage")){
				//已删除消息
				messages = userMessageService.getDeletedMessageMail(receverid,index,pageSize);
			}
			if(!BaseUtil.isSpace(messages)){
				long total = messages.size();
				return new NormalResponse(messages,total);
			}else{
				logger.debug("now {}" , "收件箱消息数据为空！");
				return new EmptyResponse("收件箱消息");
			}
		} catch (Exception e) {
			logger.error("显示所有收件箱消息出现异常：", e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	/**
	 * 显示我的消息目录结构
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("messageDir")
	@ResponseBody
	public List<MessageVo> messageDir(HttpServletRequest request,HttpServletResponse response) {
		try {
			LoginLog loginLogInfo = (LoginLog) request.getSession().getAttribute("loginLogInfo");
			int unread = userMessageService.findUnreadCountByUser(loginLogInfo.getLoginName());
			MessageVo message = new MessageVo();
			List<MessageVo> messageVos = new ArrayList<MessageVo>();
			MessageVo inbox = new MessageVo();
			inbox.setDirtype("inBox");
			if(unread>0){
				inbox.setIconCls("Emailstarted");
				inbox.setText("收件箱("+unread+")");
			}else{
				inbox.setIconCls("Emailstar");
				inbox.setText("收件箱");
			}
			inbox.setCandroponfirst(true);
			inbox.setCandroponfirst(true);
			inbox.setLeaf(true);
			messageVos.add(inbox);
			MessageVo drafts = new MessageVo();
			drafts.setDirtype("draFts");
			drafts.setText("草稿箱");
			drafts.setIconCls("Emailtransfer");
			drafts.setCandroponfirst(true);
			drafts.setCanDropOnSecond(true);
			drafts.setLeaf(true);
			messageVos.add(drafts);
			MessageVo sent = new MessageVo();
			sent.setDirtype("sentMessage");
			sent.setText("发件箱");
			sent.setIconCls("Emailstart");
			sent.setCandroponfirst(true);
			sent.setCanDropOnSecond(true);
			sent.setLeaf(true);
			messageVos.add(sent);
			MessageVo deleted = new MessageVo();
			deleted.setDirtype("deletedMessage");
			deleted.setText("垃圾桶");
			deleted.setIconCls("TrashGreenS");
			deleted.setCandroponfirst(true);
			deleted.setCanDropOnSecond(true);
			deleted.setLeaf(true);
			messageVos.add(deleted);
			message.setChildren(messageVos);
			return messageVos;
		} catch (Exception e) {
			logger.error("读取消息目录环节出现异常：", e);
			e.printStackTrace();
			return null;
		}
	}
	
	private static final String FILE_UPLOAD_DIR = "/upload";
    private static final String FILE_UPLOAD_SUB_IMG_DIR = "/img";
    private static final String FOR_RESOURCES_LOAD_DIR = "/Attachments";
    //每个上传子目录保存的文件的最大数目
    private static final int MAX_NUM_PER_UPLOAD_SUB_DIR = 500;
    //上传文件的最大文件大小
    private static final long MAX_FILE_SIZE = 1024 * 1024 * 20;
    //系统默认建立和使用的以时间字符串作为文件名称的时间格式
    private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMdd";
    //这里扩充一下格式，防止手动建立的不统一
    private static final String DEFAULT_SUB_FOLDER_FORMAT_NO_AUTO = "yyyy-MM-dd";
    
	/**
	 * 上传文件
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("upload")
	@ResponseBody
	public void upload(ModelMap modelMap,HttpServletRequest request,HttpServletResponse response) {
		// 判断提交的请求是否包含文件
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            return;
        }
        // 获取目录
        File folder = buildFolder(request,"image");
        if (null == folder) {
            return;
        }

        try {
            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            // 上传文件的返回地址
            String fileUrl = "";

            FileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            servletFileUpload.setFileSizeMax(MAX_FILE_SIZE);

            List<FileItem> fileitem = servletFileUpload.parseRequest(request);

            if (null == fileitem || 0 == fileitem.size()) {
                return;
            }

            Iterator<FileItem> fileitemIndex = fileitem.iterator();
            if (fileitemIndex.hasNext()) {
                FileItem file = fileitemIndex.next();

                if (file.isFormField()) {
                    logger.error("上传文件非法！isFormField=true");
                }

                String fileClientName = getFileName(file.getName());
                String fileSuffix = StringUtils.substring(fileClientName,
                        fileClientName.lastIndexOf(".") + 1);
                if (!StringUtils.equalsIgnoreCase(fileSuffix, "jpg")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "jpeg")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "bmp")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "gif")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "png")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "txt")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "doc")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "docx")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "xls")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "xlsx")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "csv")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "ppt")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "pptx")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "pdf")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "wps")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "et")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "dps")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "mp4")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "swf")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "mov")
                        && !StringUtils.equalsIgnoreCase(fileSuffix, "mp3")) {
                    logger.error("上传文件的格式错误{}",fileSuffix);
                    out.println("<script type=\"text/javascript\">alert('格式错误，仅支持jpg|jpeg|bmp|gif|png|txt|doc|docx|xls|xlsx|csv|ppt|pptx|pdf|wps|et|dps|mp4|swf|mov|mp3格式');</script>");
                    out.flush();
                    out.close();
                    return;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("开始上传文件:" + file.getName());
                }

                String fileServerName = generateFileName(folder, fileSuffix);
                // 为了客户端已经设置好了图片名称在服务器继续能够明确识别，这里不改名称
                File newfile = new File(folder, fileServerName);
                file.write(newfile);

                if (logger.isInfoEnabled()) {
                    logger.info("上传文件结束，新名称:" + fileServerName + ".floder:"
                            + newfile.getPath());
                }

                // 组装返回url，以便于ckeditor定位图片
                fileUrl = FOR_RESOURCES_LOAD_DIR + FILE_UPLOAD_DIR + FILE_UPLOAD_SUB_IMG_DIR + "/" + folder.getName() + "/" + newfile.getName();
                fileUrl = StringUtils.replace(fileUrl, "//", "/");
                fileUrl = request.getContextPath() + fileUrl;
    
                // 将上传的图片的url返回给ckeditor
                String callback = request.getParameter("CKEditorFuncNum");
                out.println("<script type=\"text/javascript\">");
                out.println("window.parent.CKEDITOR.tools.callFunction("
                        + callback + ",'" + fileUrl + "',''" + ")");
                out.println("</script>");
            }

            out.flush();
            out.close();

        } catch (IOException e) {
            logger.error("上传文件发生异常！", e);
        } catch (FileUploadException e) {
            logger.error("上传文件发生异常！", e);
        } catch (Exception e) {
            logger.error("上传文件发生异常！", e);
        }

        return;
	}

	private String generateFileName(File folder, String suffix) {
        String filename;
        File file;
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
        String base = format.format(date);
        filename = base + "." + suffix;
        file = new File(filename);
        int i = 1;
        while (file.exists()) {
            filename = String.format("%s_%d.%s", base, i, suffix);
            i++;
        }
        return filename;
    }
        
    /**
     * 获取文件名称
     * @param str
     * @return
     */
    private String getFileName(String str){
        int index = str.lastIndexOf("//");
        if(-1 != index){
            return str.substring(index);
        } else {
            return str;
        }
    }

	/**
	 * 创建目录
	 * @param request
	 * @return
	 */
	private File buildFolder(HttpServletRequest request,String fileType) {
		// 这里照顾一下CKEDITOR，由于ftl放置位置的原因，这里必须要在freemarker目录下才能被加载到图片，否则虽然可以正常上传和使用，但是
        // 在控件中无法正常操作
        String realPath = request.getSession().getServletContext()
                .getRealPath(FOR_RESOURCES_LOAD_DIR);

        logger.info("项目上传路径：{}",realPath);

        // 一级目录，如果不存在，创建
        File firstFolder = new File(realPath + FILE_UPLOAD_DIR);
        if (!firstFolder.exists()) {
            if (!firstFolder.mkdir()) {
                return null;
            }
        }
        // 二级目录，如果不存在，创建
        String folderdir = realPath + FILE_UPLOAD_DIR + FILE_UPLOAD_SUB_IMG_DIR;
        if(fileType.equals("file")){
        	folderdir = realPath + FILE_UPLOAD_DIR + "/file";
        }
        
        if (logger.isDebugEnabled()) {
            logger.debug("folderdir" + folderdir);
        }

        if (BaseUtil.isSpace(folderdir)) {
            logger.error("路径错误:{}",folderdir);
            return null;
        }

        File floder = new File(folderdir);
        if (!floder.exists()) {
            if (!floder.mkdir()) {
                logger.error("创建文件夹出错！path={}",folderdir);
                return null;
            }

        }
        // 再往下的文件夹都是以时间字符串来命名的，所以获取最新时间的文件夹即可
        String[] files = floder.list();
        if (null != files && 0 < files.length) {
            // 含有子文件夹，则获取最新的一个
            Date oldDate = null;
            int index = -1;
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i];

                try {
                    Date thisDate = DateUtils.parseDate(fileName, new String[] {
                            DEFAULT_SUB_FOLDER_FORMAT_AUTO, DEFAULT_SUB_FOLDER_FORMAT_NO_AUTO });
                    if (oldDate == null) {
                        oldDate = thisDate;
                        index = i;
                    } else {
                        if (thisDate.after(oldDate)) {
                            // 保存最新的时间和数组中的下标
                            oldDate = thisDate;
                            index = i;
                        }
                    }
                } catch (ParseException e) {
                    // 这里异常吃掉，不用做什么，如果解析失败，会建立新的文件夹，防止人为的建立文件夹导致的异常。
                }
            }// for

            // 判断当前最新的文件夹下是否已经存在了最大数目的图片
            if (null != oldDate && -1 != index) {
                File pointfloder = new File(folderdir + File.separator
                        + files[index]);
                if (!pointfloder.exists()) {
                    if (!pointfloder.mkdir()) {
                        logger.error("创建文件夹出错！path={}",folderdir);
                        return null;
                    }
                }

                // 如果文件夹下的文件超过了最大值，那么也需要新建一个文件夹
                String[] pointfloderFiles = pointfloder.list();
                if (null != pointfloderFiles
                        && MAX_NUM_PER_UPLOAD_SUB_DIR < pointfloderFiles.length) {
                    return buildNewFile(folderdir);
                }

                return pointfloder;
            }
            
            // 查找当前子文件夹失败，新建一个
            return buildNewFile(folderdir);
        } else {
            // 不含有子文件夹，新建一个，通常系统首次上传会有这个情况
            return buildNewFile(folderdir);
        }
	}
	
	/**
     * 创建一个新文件
     * @param path
     * @return
     */
    private File buildNewFile(String path){
        // 不含有子文件夹，新建一个，通常系统首次上传会有这个情况
        File newFile = buildFileBySysTime(path);
        if (null == newFile) {
            logger.error("创建文件夹失败！newFile={}",newFile);
        }

        return newFile;
    }

    /**
     * 根据当前的时间建立文件夹，时间格式yyyyMMdd
     * 
     * @param path
     * @return
     */
    private File buildFileBySysTime(String path) {
        DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
        String fileName = df.format(new Date());
        File file = new File(path + File.separator + fileName);
        if (!file.mkdir()) {
            return null;
        }
        return file;
    }
    
    /**
     * 上传附件
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("uploadFile")
	@ResponseBody
	public Response uploadFile(HttpServletRequest request) {
    	String fileUrl ="";
    	try{
    		// 为获取需要导入的 excel 文件，把 HttpServletRequest 转型为 MultipartHttpRequest
    		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

    		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        	// 获得 request 中上传的 excel 文件
            MultipartFile file = multipartRequest.getFile("fileName");
            //jpg|jpeg|bmp|gif|png|txt|doc|docx|xls|xlsx|csv|ppt|pptx|pdf|wps|et|dps
            if(!file.getOriginalFilename().endsWith(".jpg")
            		&&!file.getOriginalFilename().endsWith(".jpeg")
            		&&!file.getOriginalFilename().endsWith(".bmp")
            		&&!file.getOriginalFilename().endsWith(".gif")
            		&&!file.getOriginalFilename().endsWith(".png")
            		&&!file.getOriginalFilename().endsWith(".txt")
            		&&!file.getOriginalFilename().endsWith(".doc")
            		&&!file.getOriginalFilename().endsWith(".docx")
            		&&!file.getOriginalFilename().endsWith(".xls")
            		&&!file.getOriginalFilename().endsWith(".xlsx")
            		&&!file.getOriginalFilename().endsWith(".csv")
            		&&!file.getOriginalFilename().endsWith(".ppt")
            		&&!file.getOriginalFilename().endsWith(".pptx")
            		&&!file.getOriginalFilename().endsWith(".pdf")
            		&&!file.getOriginalFilename().endsWith(".wps")
            		&&!file.getOriginalFilename().endsWith(".et")
            		&&!file.getOriginalFilename().endsWith(".dps")
            		&&!file.getOriginalFilename().endsWith(".mp4")
            		&&!file.getOriginalFilename().endsWith(".swf")
            		&&!file.getOriginalFilename().endsWith(".mov")
            		&&!file.getOriginalFilename().endsWith(".mp3")){
            	return new ApplicationErrorResponse("格式错误，仅支持jpg|jpeg|bmp|gif|png|txt|doc|docx|xls|xlsx|csv|ppt|pptx|pdf|wps|et|dps|mp4|swf|mov|mp3格式");
            }
            long fileSize = file.getSize();
    		if(fileSize>MAX_FILE_SIZE){
    			return new ApplicationErrorResponse("文件太大,目前最大支持20M");
    		}
    		// 获取目录
            File folder = buildFolder(request,"file");
            String fileClientName = file.getOriginalFilename();
            String fileSuffix = StringUtils.substring(fileClientName,
                    fileClientName.lastIndexOf(".") + 1);
            String fileServerName = generateFileName(folder, fileSuffix);
            // 为了客户端已经设置好了图片名称在服务器继续能够明确识别，这里不改名称
            File newFile = new File(folder, fileServerName);
//            File newFile = new File(filePath);
            File parent = newFile.getParentFile(); 
            if(parent!=null&&!parent.exists()){ 
            	parent.mkdirs(); 
            }
    		file.transferTo(newFile);
    		String realPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
            fileUrl = realPath+FOR_RESOURCES_LOAD_DIR + FILE_UPLOAD_DIR + FILE_UPLOAD_SUB_IMG_DIR + "/" + folder.getName() + "/" + newFile.getName();
            fileUrl = request.getContextPath() + fileUrl;
    	}catch (IllegalStateException e) {
			logger.error("参数错误："+e);
			e.printStackTrace();
			return new ApplicationErrorResponse("上传失败，系统异常！");
		} catch (IOException e) {
			logger.error("文件导入错误："+e);
			e.printStackTrace();
			return new ApplicationErrorResponse("上传失败，系统异常！");
		} catch(Exception e){
			return new ApplicationErrorResponse("上传失败，系统异常！");
		}
    	return new NormalResponse(fileUrl);
    }
    
    /**
     * 保存消息草稿
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("saveMessage")
	@ResponseBody
	public Response saveMessage(HttpServletRequest request) {
    	LoginLog loginLogInfo = (LoginLog) request.getSession().getAttribute("loginLogInfo");
    	try{
    		String[] toUsers = request.getParameterValues("toUser");
    		String subject = request.getParameter("subject");
    		String content = request.getParameter("content");
    		String flag = request.getParameter("flag");
    		String fujianFlag = request.getParameter("fujianFlag");
    		if(!BaseUtil.isSpace(toUsers)&&!BaseUtil.isSpace(subject)&&!BaseUtil.isSpace(content)){
    			//保存消息
    			MessAge message = new MessAge();
    			message.setMessage_title(subject);
    			message.setMessage_text(content);
    			if(!BaseUtil.isSpace(fujianFlag)&&fujianFlag.equals("attachment")){
    				message.setAttachment("1");
    			}else{
    				message.setAttachment("0");
    			}
        		message.setMessage_type(EnumStatus.AVAILABLE);
            	messageService.saveMessage(message);
            	//保存消息对应的收发件人关系
        		for(int i =0;i<toUsers.length;i++){
        			UserMessage um = new UserMessage();
                	um.setMessage_id(message.getMessage_id());
                	um.setSend_user(loginLogInfo.getLoginName());
                	um.setReceverid_user(toUsers[i]);
                	um.setSend_status(EnumStatus.DELETE);
                	if(!BaseUtil.isSpace(flag)&&flag.equals("reply")){
                		um.setReceverid_status(EnumStatus.AVAILABLE);
                	}else{
                		um.setReceverid_status(EnumStatus.DISABLED);
                	}
                	
                	um.setRead_status(EnumStatus.AVAILABLE);
                	userMessageService.saveUserMessage(um);
        		}
    		}
    	}catch(Exception e){
    		logger.error("保存草稿错误："+e);
			e.printStackTrace();
			return new ApplicationErrorResponse("保存失败，系统异常！");
    	}
    	
    	return new NormalResponse();
    }
    /**
     * 发送消息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("sendMessage")
	@ResponseBody
	public Response sendMessage(HttpServletRequest request) {
    	LoginLog loginLogInfo = (LoginLog) request.getSession().getAttribute("loginLogInfo");
    	try{
    		String[] toUsers = request.getParameterValues("toUser");
    		String subject = request.getParameter("subject");
    		String content = request.getParameter("content");
    		String flag = request.getParameter("flag");
    		String fujianFlag = request.getParameter("fujianFlag");
    		if(!BaseUtil.isSpace(toUsers)&&!BaseUtil.isSpace(subject)&&!BaseUtil.isSpace(content)){
    			//保存消息
    			MessAge message = new MessAge();
    			message.setMessage_title(subject);
    			message.setMessage_text(content);
    			if(!BaseUtil.isSpace(fujianFlag)&&fujianFlag.equals("attachment")){
    				message.setAttachment("1");
    			}else{
    				message.setAttachment("0");
    			}
        		message.setMessage_type(EnumStatus.AVAILABLE);
            	messageService.saveMessage(message);
            	
            	//保存消息对应的收发件人关系
        		for(int i =0;i<toUsers.length;i++){
        			UserMessage um = new UserMessage();
                	um.setMessage_id(message.getMessage_id());
                	um.setSend_user(loginLogInfo.getLoginName());
                	um.setReceverid_user(toUsers[i]);
                	um.setSend_status(EnumStatus.AVAILABLE);
                	if(!BaseUtil.isSpace(flag)&&flag.equals("reply")){
                		um.setReceverid_status(EnumStatus.AVAILABLE);
                	}else{
                		um.setReceverid_status(EnumStatus.DISABLED);
                	}
                	um.setRead_status(EnumStatus.DISABLED);
                	userMessageService.saveUserMessage(um);
        		}
    		}
    	}catch(Exception e){
    		logger.error("发送消息错误："+e);
			e.printStackTrace();
			return new ApplicationErrorResponse("发送消息失败，系统异常！");
    	}
    	
    	return new NormalResponse();
    }
    
    /**
     * 阅读消息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("readMessage")
	@ResponseBody
	public Response readMessage(HttpServletRequest request) {
    	String messageId = request.getParameter("messageId");
    	LoginLog loginLogInfo = (LoginLog) request.getSession().getAttribute("loginLogInfo");
    	UserMessage ms = new UserMessage();
    	ms.setReceverid_user(loginLogInfo.getLoginName());
    	ms.setMessage_id(messageId);
    	UserMessage ums = userMessageService.findUserMessAge(ms);
    	if(ums!=null){
    		if(ums.getRead_status().equals(EnumStatus.DISABLED)){
        		ums.setRead_status(EnumStatus.AVAILABLE);
        	}
        	userMessageService.updateUserMessageById(ums);
        	MessAge msa = new MessAge();
        	msa.setMessage_id(messageId);
        	MessAge msage = messageService.findMessAge(msa);
        	ums.setMessage_title(msage.getMessage_title());
        	ums.setMessage_text(msage.getMessage_text());
        	ums.setSend_time(msage.getSend_time());
    	}else{
    		ms.setReceverid_user(null);
    		ms.setSend_user(loginLogInfo.getLoginName());
    		ums = userMessageService.findUserMessAge(ms);
    		if(ums!=null){
        		if(ums.getRead_status().equals(EnumStatus.DISABLED)){
            		ums.setRead_status(EnumStatus.AVAILABLE);
            	}
            	userMessageService.updateUserMessageById(ums);
            	MessAge msa = new MessAge();
            	msa.setMessage_id(messageId);
            	MessAge msage = messageService.findMessAge(msa);
            	ums.setMessage_title(msage.getMessage_title());
            	ums.setMessage_text(msage.getMessage_text());
            	ums.setSend_time(msage.getSend_time());
        	}
    	}
    	return new NormalResponse(ums);
    }
    
    /**
     * 删除消息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("delMessage")
	@ResponseBody
	public Response delMessage(HttpServletRequest request) {
    	try {
			Context context = new RequestContext(request);
			messageService.deleteMessageBymessageId(context);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("删除用户环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
    }
    
	/**
	 * 收件箱消息全部标记为已读
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("hasRead")
	@ResponseBody
	public Response hasRead(HttpServletRequest request,HttpServletResponse response) {
		try {
			LoginLog loginLogInfo = (LoginLog) request.getSession().getAttribute("loginLogInfo");
			String receverid = loginLogInfo.getLoginName();
			UserMessage usermessage = new UserMessage();
			usermessage.setReceverid_user(receverid);
			List<UserMessage> messages = userMessageService.findUnreadListByUser(usermessage);
			if(!BaseUtil.isSpace(messages)){
				for(UserMessage um:messages){
					um.setRead_status(EnumStatus.AVAILABLE);
					userMessageService.updateUserMessageById(um);
				}
				return new NormalResponse();
			}else{
				return new EmptyResponse("未读消息");
			}
		} catch (Exception e) {
			logger.error("收件箱消息全部标记为已读出现异常：", e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	/**
	 * 清空所有消息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("delAllRead")
	@ResponseBody
	public Response delAllRead(HttpServletRequest request,HttpServletResponse response) {
		try {
			LoginLog loginLogInfo = (LoginLog) request.getSession().getAttribute("loginLogInfo");
			String receverid = loginLogInfo.getLoginName();
			List<UserMessage> messages = userMessageService.findListByUser(receverid);
			if(!BaseUtil.isSpace(messages)){
				for(UserMessage um:messages){
					um.setSend_status(EnumStatus.DELETE);
					userMessageService.updateUserMessageById(um);
				}
				return new NormalResponse();
			}else{
				return new EmptyResponse("可删除消息");
			}
		} catch (Exception e) {
			logger.error("清空所有消息出现异常：", e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
}

